package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    private static final String CACHE_KEY_FREEZE_PREFIX = "FREEZE_KEY_";

    //本类的日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    //json转换
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HuanXinService huanXinService;


    /**
     * @param mobile
     * @param code
     * @return 如果效验成功就返回token, 失败返回null
     */
    public String login(String mobile, String code) {
        //效验验证码是否正确
        //查看redis中是否存在该tekon信息
        String redisKey = "CHECK_CODE_" + mobile;
        String value = this.redisTemplate.opsForValue().get(redisKey);
        //如果值为空
        if (StringUtils.isEmpty(value)) {
            //验证码失效
            return null;
        }

        //不为空则判断value和code是否相等
        if (!StringUtils.equals(value, code)) {
            //验证码输入错误
            return null;
        }

        //定义标记,默认已注册
        Boolean isNew = false;

        //效验该手机号是否已经注册,如果没有注册,需注册一个账号,已经注册.直接登入

        //创建查询构建器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        User user = this.userMapper.selectOne(queryWrapper);


        if (null == user) {
            //该手机号没注册,注册
            //创建新对象
            user = new User();
            //设置手机号初始密码
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            //最后添加到数据库中
            this.userMapper.insert(user);

            isNew = true;
            redisTemplate.delete(redisKey);

            //注册用户到环信平台
            huanXinService.register(user.getId());
        }

        //设置查询redis的key
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + user.getId().toString();
        //根据key去查询redis,判断用户是否被冻结
        String key = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.equals(key,"1")){
            return null;
        }


        HashMap<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("id", user.getId());

        //生成token
        String token = Jwts.builder()
                .setClaims(map)   //设置响应数据体
                .signWith(SignatureAlgorithm.HS256, secret)  //设置加密方法和加密盐
                .compact();

        try {
            //将token存入到redis中
            String redisTokenKey = "TOKEN_" + token;
            //将对象转成json字符串
            String redisTokenValue = MAPPER.writeValueAsString(user);
            //存入redis中
            redisTemplate.opsForValue().set(redisTokenKey, redisTokenValue, Duration.ofHours(1));
        } catch (Exception e) {
            LOGGER.error("存储token出错", e);
            return null;
        }

        //发送消息
        try {
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("mobile", mobile);
            msg.put("date", new Date());
            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (Exception e) {
            LOGGER.error("发送消息出错", e);
        }

        return isNew + "|" + token;
    }

    /**
     * 定时检测用户是否在线
     *
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        try {
            String redisTokenKey = "TOKEN_" + token;
            //获取到redis中token的值
            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isEmpty(cacheData)) {
                return null;
            }

            //刷新时间
            this.redisTemplate.expire(redisTokenKey, 1, TimeUnit.HOURS);
            //将json对象转成user对象
            return MAPPER.readValue(cacheData, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 保存新手机号码
     *
     * @param id
     * @param newPhone
     * @return
     */
    public boolean updatePhone(Long id, String newPhone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user != null) {
            // 改手机号已经存在
            return false;
        }
        user = new User();
        user.setId(id);
        user.setMobile(newPhone);
        return this.userMapper.updateById(user) > 0;
    }
}
